﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Clandestine.Graphics
{
	public abstract partial class Renderable
	{
		private const decimal depthStep = 0.00000000001M; // so, can't have depths bigger than 1 times 10^19 or so.
		private decimal depth = decimal.MinValue;

		public decimal Depth
		{
			get { return depth; }
			set
			{
				// They ARE actually making a change, right?
				if (depth != value)
				{
					graphics.BlockRendering();

					if (renderList.Contains(this))
						renderList.Remove(this);

					depth = findUniqueDepthLike(value);
					renderList.Add(this);

					graphics.UnblockRendering();
				}
			}
		}

		private decimal findUniqueDepthLike(decimal depth)
		{
			graphics.BlockRendering();

			if (renderList.ContainsKey(depth))
			{
				// Hey, now. Decimal DOES have 29 significant figures of precision...
				// Also, the reason we're using SortedList<> not SortedDictionary<> is it's supposed to have 
				// faster Key access.  Maybe.  I wasn't paying too much attention, I must confess.
				while (renderList.ContainsKey(depth))
					depth += depthStep;
			}

			graphics.UnblockRendering();

			return depth;
		}
	}
}
